#ifndef GETIMAGE_H
#define GETIMAGE_H

#include <QObject>
#include <QHttp>
#include <QList>
#include <QBuffer>
#include <QDir>
#include <QPixmap>

#define DEFAULT_CACHE_DATA_FILE "cache.data"

class CacheData {

    public:
        QString screen_name;
        QString modify_time;
        QString etag;
        QString md5;
};

class GetImage : public QObject {
    Q_OBJECT
public:
    GetImage(QObject *parent = 0);
    ~GetImage();
    void SetCacheDir(QString cachedir);
    void AddImageData(QString screen_name, QString url);

    enum ERROR {
        // Can`t create dir for cache
        CANT_CREATE_DIR,
        // Can`t write image to cache dir
        CANT_CREATE_IMAGE_FILE,
        // Can`t write to cache data file
        CANT_CREATE_CACHE_FILE,
        // Can`t read cache data file
        CANT_READ_CACHE_DATA,
        // Cache dir not set
        CACHE_DIR_NOT_SET,
        // Wrong image has been downloaded
        WRONG_IMAGEDATA
    };

    enum RESPONSE {
        OK = 200,
        NOT_MODIFIED = 304,
        BAD_REQUEST = 400,
        NOT_AUTHORIZED = 401,
        FORBIDDEN = 403,
        NOT_FOUND = 404,
        INTERNAL_SERVER_ERROR = 500,
        BAD_GATEWAY = 502,
        SERVICE_UNAVAILABLE = 503
   };

private:
    QHttp *http;
    QPair<int, QBuffer*> data;
    void MakeRequest(const QString &url,const QString &modify_time = "",const QString &etag = "");
    void responseHeaderReceived(const QHttpResponseHeader &resp_header);
    QString currentCacheDir;

    void loadCache(QDir &dir);
    QList<CacheData*> cacheDataList;

    QList<QPair<QString, QString> > userDatalist;
    void findCachedFile(QString &screen_name);

    int saveImageToCache(QByteArray &imagedata,QString &modify_time, QString &etag, QString &md5);

    void prepareRequest();
    void theNext();

private slots:
    void requestFinished(int id, bool error);

signals:
    void error(GetImage::ERROR error);
    void imageReady(QString screen_name, QPixmap image);

};

#endif // GETIMAGE_H
